import md5 from 'js-md5'
import qs from 'qs'
import axios from 'axios'
import Cookies from 'js-cookie'

function encryption2(params, url) {
  const promise = new Promise(function(resolve, reject) {
    const timestamp = (Date.parse(new Date()) / 1000).toString()
    // console.log(Cookies.get('userinfo_Gulid'));
    if (Cookies.get('userinfo_Gulid')) {
      params.owner = JSON.parse(Cookies.get('userinfo_Gulid')).guild_info.owner
      params.token = JSON.parse(Cookies.get('userinfo_Gulid')).token
      params.guildId = JSON.parse(Cookies.get('userinfo_Gulid')).guild_info.guild_id
    }
    params.time = timestamp
    const _token = EncryptedCharacter(params)
    params.sign = md5(_token)
    axios.post(url, qs.stringify(params))
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
  return promise
}

function EncryptedCharacter(arys) {
  var param = reverse(arys)
  var extra_str = '&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX'
  if (Object.prototype.toString.call(param) !== '[object Object]') {
    return ''
  }
  let queryParam = ''
  for (const key in param) {
    if (param.hasOwnProperty(key)) {
      const value = param[key]
      // if (value) {
      //   queryParam += toQueryPair(key, value.toString());
      // }
      queryParam += toQueryPair(key, value)
    }
  }
  return queryParam.slice(1) + extra_str
}
// 数组转字符串完成加密
function toQueryPair(key, value) {
  if (typeof value === 'undefined') {
    return `&${key}=`
  }
  return `&${key}=${value}`
}
// 对象转数组并倒序
function reverse(arys) {
  var newkey = Object.keys(arys).sort().reverse()
  var newObj = {}
  for (var i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = arys[newkey[i]]
  }
  return newObj
}
export {
  encryption2
}
